package com.example.Arithmetic.Arithmetic;


import java.util.Arrays;

/**
 * 日期：2023/10/12
 * 时间：9:28
 * 描述：大顶堆的实现
 */
public class MaxHeap {
    int[] array;
    int size;

    public MaxHeap(int capacity) {
        this.array = new int[capacity];
    }

    public MaxHeap(int array[]) {
        this.array = array;
        this.size = array.length;
        heapify();
    }

    public int peek() {
        return array[0];
    }

    //    移除元素
    public int poll() {
        if (isEmpty()) {
            return Integer.parseInt(null);
        }
        int i = array[0];
        swap(0, size - 1);
        down(0);
        size--;
        return i;
    }

    //    根据索引移除元素
    public int poll(int index) {
        if (isEmpty()) {
            return Integer.parseInt(null);
        }
        int i = array[index];
        swap(index, size - 1);
        down(index);
        size--;
        return i;
    }

    //    替换堆顶元素
    public void replace(int replaced) {
        array[0] = replaced;
        down(0);
    }

    //    堆尾添加元素
    public boolean offer(int offered) {
        if (size == array.length) {
            return false;
        }
        up(offered);
        size++;
        return true;
    }

    private void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (child - 1) / 2;
            if (offered > array[parent]) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    private void heapify() {
//        找到最后一个非叶子节点
        //最后一个节点除以2-1
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(i);
        }
    }

    public boolean isEmpty() {
        return size == 0;
    }

    private void down(int parent) {
        int left = parent * 2 + 1;
        int right = left + 1;
        int max = parent;
        if (left < size && array[max] < array[left]) {
            max = left;
        }
        if (right < size && array[max] < array[right]) {
            max = right;
        }
//        不等于父元素，证明值更改了，需要交换
        if (max != parent) {
            swap(max, parent);
            down(max);
        }
    }

    public void swap(int i, int j) {
        int t = array[i];
        array[i] = array[j];
        array[j] = t;
    }

    public static void main(String[] args) {
//        堆排序
        int[] array = new int[]{1, 2, 5, 5, 5, 4, 5, 7, 8, 9};
        MaxHeap maxHeap = new MaxHeap(array);
        System.out.println(Arrays.toString(maxHeap.array));
        while (maxHeap.size > 1) {
            maxHeap.swap(0, maxHeap.size - 1);
            maxHeap.size--;
            maxHeap.down(0);
        }
        System.out.println(Arrays.toString(maxHeap.array));
    }

}
